package main

import (
	"../common/message"
	"../common/utils"
	"encoding/json"
	"fmt"
	"net"
)

func login(userID int, userPwd string) (err error) {

	conn, err := net.Dial("tcp", "localhost:8888")

	if err != nil {
		fmt.Printf("conn error = %v", err)
		return
	}

	defer conn.Close()

	var mes message.Message
	mes.Type = message.LoginMesType

	var loginMes message.LoginMes
	loginMes.UserID = userID
	loginMes.UserPwd = userPwd

	data, err := json.Marshal(loginMes)
	if err != nil {
		fmt.Printf("json marshal loginMes error = %v\n", err)
		return
	}

	mes.Data = string(data)

	data, err = json.Marshal(mes)
	if err != nil {
		fmt.Printf("json marshal mes error = %v\n", err)
		return
	}

	err = utils.WritePkg(conn, data)
	if err != nil {
		fmt.Printf("conn write data error = %v\n", err)
		return
	}

	fmt.Printf("客户端发送消息内容 = %v\n", string(data))

	msg, err := utils.ReadPkg(conn)
	if err != nil {
		fmt.Printf("readPkg error = %v\n", err)
		return
	}

	var loginResMes message.LoginResMes
	err = json.Unmarshal([]byte(msg.Data), &loginResMes)
	if err != nil {
		fmt.Printf("loginResMes json.Unmarshal error = %v\n", err)
		return
	}

	if loginResMes.Code == 200 {
		fmt.Println("登陆成功")
	} else {
		fmt.Println(loginResMes.Error)
	}

	return
}
